package com.quanyan.user.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.GsonUtils;
import com.quanyan.common.utils.HttpUtils;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.messagepush.entity.*;
import com.quanyan.messagepush.enums.BoxName;
import com.quanyan.messagepush.enums.BoxType;
import com.quanyan.messagepush.enums.IdType;
import com.quanyan.messagepush.enums.MsgType;
import com.quanyan.mq.client.QcMsgClient;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.user.cache.MyRedisTemplate;
import com.quanyan.user.model.db.TbUser;
import com.quanyan.user.mq.UserTaskMsg;
import com.quanyan.user.service.SendMsgService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/11/23.
 */
@Service
public class SendMsgServiceImpl implements SendMsgService {
    private static Logger logger = LoggerFactory.getLogger(SendMsgService.class);

    @Resource(name = "qcMsgClient")
    private QcMsgClient qcMsgClient;

    @Value("${message.push.service.url}")
    public String messagePushServiceUrl;

    @Autowired
    private MyRedisTemplate myRedisTemplate;


    String kGetDynamicDetailUrl = "/dynamic/dynamicDetail.api";

    @Override
    public void sendUserTaskMsg(UserTaskMsg userTaskMsg) {
        logger.info(" send user center task msg start===》{}",userTaskMsg.toString());
        MqRequestMsg mqRequestMsg = new MqRequestMsg();
        mqRequestMsg.setTopic(Constants.MQ_TOPIC_TASK_TOPIC);
        mqRequestMsg.setTag(Constants.MQ_TOPIC_TASK_TAG);
        mqRequestMsg.setBody(ObjectUtil.toByteArray(userTaskMsg));
        qcMsgClient.asyncSend(mqRequestMsg);
        logger.info(" send user center task msg end===》{}");

    }

    /**
     *
     * @param currentUser 当前用户
     * @param toUid @用户
     * @param dynamicDetailsId 动态id
     * @param commentContent 评论内容
     * @param boxType 类型
     * @return
     */
    public boolean pushDynamicMsg(TbUser currentUser ,Integer dynamicUid,Integer toUid ,Integer  dynamicDetailsId ,String commentContent,int boxType,String imgUrl){
        String flag = (String)myRedisTemplate.get(push_flag_key);
        if (flag.equals(push_flag_value_OFF)){
            logger.info("推送开关========================> 当前状态是关闭状态 {}",flag);
            return false;
        }

        logger.info("push msg ==========================>start");
        if(boxType !=BoxType.REPLY_MSG.value() &&currentUser.getId().intValue() == dynamicUid.intValue() ){
            logger.info("给自己点赞，评论，回复不推送消息");
            return false;
        }

        logger.info("push msg dynamic boxType ：{},commentContent {},imgUrl {}",boxType,commentContent,imgUrl);
        String boxTitle  = String.format("“%s”评论了你的动态", currentUser.getNickName());
        String lockTitle = "评论：" + boxTitle;
        List<Integer> lstUid = new ArrayList<>(); // 发送消息

        if (boxType == BoxType.REPLY_MSG.value()) {
            boxTitle = String.format("“%s”回复了你的评论", currentUser.getNickName());
            lockTitle = "回复：" + boxTitle;
            lstUid.add(toUid);
        }else  if (boxType == BoxType.COMMENTS_MSG.value()){
            lstUid.add(dynamicUid);
             boxTitle  = String.format("“%s”评论了你的动态", currentUser.getNickName());
             lockTitle = "评论：" + boxTitle;
        }else   if (boxType == BoxType.PRAISE_MSG.value()){
            lstUid.add(dynamicUid);
            boxTitle  = String.format("“%s”赞了你的动态", currentUser.getNickName());
            lockTitle = "赞：" + boxTitle;
        }

        Jump jump = new Jump();
        jump.setIdType(IdType.DYNAMIC_DETAIL.value());
        Map<String,Object> map = new HashMap<>();
        map.put("dynamicDetailsId",dynamicDetailsId);
        jump.setParam(map);

        Payload payload = new Payload();
        payload.setTitle(boxTitle);
        payload.setBoxType(boxType);
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setJump(jump);
        payload.setUrl(kGetDynamicDetailUrl);
        payload.setImg(currentUser.getIcon());
        payload.setNickname(currentUser.getNickName());

        Map<String,Object> newImgMap = new HashMap<>();
        if(imgUrl != null && !"".equals(newImgMap))
            newImgMap.put("newsImage",imgUrl);
        newImgMap.put("uid",currentUser.getId());
        payload.setExtend(newImgMap);

        if (boxType == BoxType.COMMENTS_MSG.value())
            payload.setBody("评论: " + commentContent );
        else  if (boxType == BoxType.REPLY_MSG.value())
            payload.setBody("回复: " + commentContent );
        else  if (boxType == BoxType.PRAISE_MSG.value())
            payload.setBody( "赞了你的动态");

        logger.info("开始推送消息：{}");
        return baseDatesportMessage(lstUid, lockTitle, boxTitle, payload);
    }


    private boolean baseDatesportMessage(List<Integer> uidList, String lockTitle, String boxTitle, Payload payload) {
        Alert alert = new Alert();
        alert.setTitle("百灵鸟");
        alert.setBody(lockTitle);

        PushMessage message = new PushMessage();
        message.setTag(BoxName.SPORTS.value() + "_" + System.currentTimeMillis());
        message.setAlert(alert);
        message.setTo(uidList);
        message.setLogo("lark_icon.png");
        message.setPayload(payload);

        ReqPushMessage reqPushMessage = new ReqPushMessage();
        List<PushMessage> messages = new ArrayList<PushMessage>();
        messages.add(message);
        reqPushMessage.setMsgList(messages);

        String reqStr = GsonUtils.toJson(reqPushMessage);
        String responStr = HttpUtils.sendWebRequestByPostJsonStr(null, messagePushServiceUrl, reqStr, 30000);
        if (StringUtil.isBlankOrNull(responStr) || !StringUtil.isJsonStr(responStr)) {
            logger.info("动态消息：调用C++消息推送服务返回为空或不为json字符串。请求：{}。晌应：{}。", reqStr, responStr);
            return false;
        }
        JSONObject jo = JSON.parseObject(responStr);
        boolean isSuccess = jo.getBoolean("ret");
        if (!isSuccess) {
            logger.info("动态消息：调用消息推送服务异常。请求：{}。晌应：{}", reqStr, responStr);
        } else {
            logger.info("动态消息：调用消息推送成功。请求：{}。晌应：{}", reqStr, responStr);
        }
        logger.info("push msg ==========================>start");
        return isSuccess;
    }

    @Override
    public void initPushFlag() {
        String flag = (String)myRedisTemplate.get(push_flag_key);
        logger.info("推送开关==========》当前的状态================》：{}",flag);
        if (flag == null){
            logger.info("推送开关=====》 为空================》开始设置：{}",flag);
            myRedisTemplate.set(push_flag_key,push_flag_value_ON);
            logger.info("推送开关=====》 为空================》结束设置：{}",(String)myRedisTemplate.get(push_flag_key));
        }

    }
}
